# -*- coding: utf-8 -*-
#from google.appengine.dist import use_library
#use_library('django', '1.3')
#use_library('jinja2', '2.6')
#_MAXCACHE=500
'''
runtime: python27
threadsafe: true
libraries:                                                                      
- name: jinja2                                                                  
  version: latest
- name: pycrypto
  version: latest
- name: setuptools
  version: latest
- name: lxml
  version: latest
'''
import json
from google.appengine.api import memcache
from google.appengine.api.app_identity import *
from webapp2_extras import jinja2
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import webapp2 as webapp
from google.appengine.api import urlfetch
import os,re,urllib,logging,sys,traceback
from HTMLParser import HTMLParser
class BaseRequestHandler(webapp.RequestHandler):
    @webapp.cached_property
    def jinja2(self):
        #Gae.logE(jinja2.default_config)
        jinja2.default_config['template_path']=''
        return jinja2.get_jinja2(app=self.app)
    def __init__(self,req=None,res=None):
        if hasattr(req,'request') and res==None:
            self.initialize(req.request,req.response)
        else:
            super(BaseRequestHandler,self).__init__(req,res)
    def render2(self,template_file,template_val = {}):
        for k in template_val:
            if type(template_val[k])==type(''):
                template_val[k]=template_val[k].decode('utf8')
        #Gae.logE(jinja2.default_config)
        self.write(self.jinja2.render_template(template_file, **template_val))
        #self.write(template.render(os.path.join(os.path.dirname(pathname), template_file),template_val))
    def write(self,s):
        self.response.out.write(s)
    def initialize(self, request, response):
        super(BaseRequestHandler,self).initialize(request,response)
        #self.request                            = request
        #self.response                           = response
        self.url                                = request.url
        self.remote_addr                        = request.remote_addr
        self.body_file                          = request.body_file
        self.body                               = request.body
        self.path                               = request.path
        self.query_string                       = request.query_string
        self.qs =   self.query_string
        self.headers                            = request.headers
        self.cookies                            = dict(request.cookies)
        self.rspheader  =self.response.headers
        self.cookie=''
        if 'Cookie' in self.headers:
            self.cookie=self.headers['Cookie']
        self.UA =   self.headers['User-Agent']
    def cache(self,t=3600):
        self.rspheader['Cache-Control']='public, max-age=%d'%t
    def nocache(self):
        self.rspheader['Cache-Control']='no-cache,no-store'
        self.rspheader['Expires']='0'
    def getquery(self,param,case=False):
        return self.getq(param,case)
    def addheader(self,header,value):
        value=Gae.toS(value)
        self.response.headers.add_header(header,value)
    def getq(self,param,case=False):
        ret=Gae.toS(self.request.get(param))
        if case:
            return ret
        else:
            return ret.lower()
    def get_all(self,param):
        return self.request.get_all(param)
    def jsonwrite(self,s,asc=False):
        self.write(json.dumps(s,ensure_ascii=asc))
    def Parse(self,params):
    	self.P={}
    	for i in params:
    		self.P[i]=self.getq(i)
    def copyheader(headers):
        for header in headers:
            if self.headers.has_key(header):
                self.rspheader[header]=self.headers[header]
    def err(self):
        self.error(500)
    def code(self,c,s):
        self.response.set_status(c,message=s)
    def clear(self):
        self.response.clear()
    def outval(self):
        return self.response.body
class Gae:
    @staticmethod
    def mget(o):
        return memcache.get(o)
    @staticmethod
    def mset(o,v,t=6000):
        memcache.set(o,v,t)
    @staticmethod
    def tb():
        traceback.print_exc()
    @staticmethod
    def getCodeLine():
        return sys._getframe().f_back.f_back.f_lineno
    @staticmethod
    def getCodeName():
        return sys._getframe().f_back.f_back.f_code.co_name
    @staticmethod
    def appurl():
        return 'http://%s.appspot.com'%Gae.id()
    @staticmethod
    def id():
        return get_application_id()
    @staticmethod
    def isdev():
        #Gae.logD(os.environ['SERVER_SOFTWARE'])
        return 'Development' in os.environ['SERVER_SOFTWARE']
    @staticmethod
    def run(url_mapping, debug                  = False):
        app  = webapp.WSGIApplication(url_mapping, debug)
        return app
    @staticmethod
    def str2u(s):
        if type(s)==type(u''):
            return s
        return s.decode('gb18030').encode('utf-8')
    @staticmethod
    def tryCode(s):
        ret=s
        try:
            ret=Gae.uni(s)
        except:
            pass
        try:
            ret=Gae.str2u(ret)
        except:
            pass
        try:
            ret=s.decode('utf8').encode('gb18030')
        except:
            pass
        return s
    @staticmethod
    def uni(s):
        return Gae.toU(s)
    @staticmethod
    def toU(s):
        if type(s)==type(u''):
            return s
        try:
            return s.decode('utf8')
        except:
            try:
                return s.decode('gb18030')
            except:
                return s
    @staticmethod
    def toS(s):
        if type(s)==type(''):
            return s
        try:
            return s.encode('utf8')
        except:
            try:
                return s.encode('gb18030')
            except:
                return s
    @staticmethod
    def find(s,patterns):
        try:
            return re.findall(patterns,s,re.DOTALL)
        except Exception,e:
            Gae.logE(patterns)
            Gae.logE(e)
            return []
    @staticmethod
    def search(s,patterns):
        return re.search(patterns,s,re.DOTALL)
    @staticmethod
    def delline(s):
        return s.replace('\r','').replace('\n','')
    @staticmethod
    def url(url,str_filter=None,**k):
        try:
            result                                  = urlfetch.fetch(url=url,deadline=500,**k)
        except:
            return None
        if result.status_code==200:
            if str_filter:
                return str_filter(result.content)
            return result.content
        return None
        #result.status_code
    @staticmethod
    def urlfind(url,patterns,findmode           = True,str_filter=None):
        result                                  = Gae.url(url,str_filter)
        if result==None:
            return []
        if findmode:
            findresult                          = Gae.find(result,patterns)
            return findresult
        findresult                          = Gae.search(result,patterns)
        if findresult ==None:
            	return []
        return [i for i in findresult.groups()]
    @staticmethod
    def urljson(url,**k):
        result                                  = Gae.url(url,**k)
        if result==None:
            return None
        return json.loads(result)
    @staticmethod
    def logE(s):
        s='%s:%d,%s'%(Gae.getCodeName(),Gae.getCodeLine(),s)
        logging.error(s)
    @staticmethod
    def logD(s):
        s='%s:%d,%s'%(Gae.getCodeName(),Gae.getCodeLine(),s)
        logging.debug(s)
    @staticmethod
    def logL(s):
        s='%s:%d,%s'%(Gae.getCodeName(),Gae.getCodeLine(),s)
        logging.log(s)
    @staticmethod
    def logI(s):
        s='%s:%d,%s'%(Gae.getCodeName(),Gae.getCodeLine(),s)
        logging.info(s)
    @staticmethod
    def logW(s):
        s='%s:%d,%s'%(Gae.getCodeName(),Gae.getCodeLine(),s)
        logging.warning(s)
    @staticmethod
    def encode(s):
        return urllib.urlencode(s)
    @staticmethod
    def unescape(s):
        if '&' not in s:
            return s
        def replaceEntities(s):
            s = s.groups()[0]
            try:
                if s[0] == "#":
                    s = s[1:]
                    if s[0] in ['x','X']:
                        c = int(s[1:], 16)
                    else:
                        c = int(s)
                    return unichr(c)
            except:
                return '&#'+s+';'
        try:
            s=Gae.uni(s)
        except:
            return s
        try:
            s=Gae.str2u(s)
        except:
            return s
        return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]{1,8}));", replaceEntities, s)
    @staticmethod
    def sortmap(s):
        t=s.keys()
        t.sort()
        return [(x,s[x]) for x in t]
    @staticmethod
    def refind(regx,s):
        return Gae.find(s,regx)
